package analyzer;

import Util.SortedHashtable;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

public class AnalyzerAgent {

    private int index;
    private String name;
    int VERDE = 1;
    int ROJO = 0;
    int AMBAR = 3;
    int SE = 1; //Stop Event

    int CE = 2;//Cross Event
    int LCE = 3; //Light Change Event

    int CLE = 5; //Change Lane Event

    int CLEE = 6; //Change Lane End Event

    int ALE = 7; //Arrival Link Event

    int LLE = 8; //Leave Link Event

    int BE = 9; //Begin Event

    int AE = 10; //Arrival Event

    int WSE = 11; //Warning Event, as a stop event, but dont stop

    int WBE = 12; // warning Event, as a begin event, but actually for a dont stop event

    private String pathLog = "c:/temp/log.txt";
    public SortedHashtable elementsInAnalysis;
    String objectID;
    double evTime;
    int segment;
    double evPos;
    int evType;
    private int n;
    private double t;

    public AnalyzerAgent() {

        this.name = "Analyzer Agent" + index;
        elementsInAnalysis = new SortedHashtable();

    }

    public String toString() {
        return this.name;
    }

    public void getDensityFlowLog_ver1(int segToAnalyze, double p, double measurementArea, String pathOut) {
        BufferedReader entrada = null;

        String[] result;

        double limitPeriod = p;
        double q = 0, d = 0;
        double nQ = 0, nD = 0;



        File f = new File(pathLog);

        try {
            entrada = new BufferedReader(new FileReader(f));
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        if (f.exists()) {
            try {

                FileOutputStream out = new FileOutputStream(pathOut, true);

                PrintWriter miArchivo = new PrintWriter(out);
                miArchivo.write("Densidad" + "\t");
                miArchivo.write("Flujo" + "\t");


                miArchivo.println();
                miArchivo.close();

                System.out.println(entrada.readLine());



                String s;
                while ((s = entrada.readLine()) != null) {
                    //Separar campos
                    result = s.split(",");
                    objectID = result[0];
                    System.out.println(objectID);
                    evTime = Double.valueOf(result[1]).doubleValue();
                    segment = Integer.valueOf(result[2]).intValue();
                    evPos = Double.valueOf(result[3]).doubleValue();
                    evType = Integer.valueOf(result[4]).intValue();
                    if (segment == segToAnalyze) {

                        while (evTime > limitPeriod) {

                            nD = getNumberOfIIA();
                            d = nD / measurementArea;
                            out = new FileOutputStream("c:/temp/logQD_ver1.txt", true);

                            miArchivo = new PrintWriter(out);
                            miArchivo.write(d + "\t");
                            miArchivo.write(q + "\t");


                            miArchivo.println();
                            miArchivo.close();

                            //log d y q
                            q = 0;
                            limitPeriod = limitPeriod + p;
                        }
                        if (evType == CE) {
                            System.out.println(objectID);
                            if (searchIIA(objectID) != false) {
                                removeIIA(objectID);
                                nQ++;
                                q = nQ / p;

                            }
                        } else {
                            if (evType == ALE || evType == AE) {
                                //System.out.println(objectID); 
                                if (searchIIA(objectID) == false) {
                                    addIIA(objectID);
                                }
                            }
                        }

                    }

                }
                System.out.println("Finished Analysis");


            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public boolean removeIIA(Object itemID) {
        elementsInAnalysis.remove(itemID);
        return true;
    }

    public boolean addIIA(Object itemID) {
        // System.out.println(itemID); 
        elementsInAnalysis.put(itemID, 0.0);
        return true;
    }

    public int getNumberOfIIA() {
        return elementsInAnalysis.size();

    }

    public boolean searchIIA(Object itemID) {
        boolean b = false;
        try {
            b = elementsInAnalysis.containsKey(itemID);
        } catch (NullPointerException ex) {
            System.out.println("itemID is null");
        }

        return b;
    }

    public void getDensityFlowLog_ver2(int segToAnalyze, double p, String pathOut) {
        BufferedReader entrada = null;

        String[] result;

        double limitPeriod = p;
        double q = 0, d = 0;
        //variables que almacenan la densidad y el flujo
        double nQ = 0, nD = 0;
        //variables que almacenan el numero de vehiculos que han cruzado nQ
        // y numero de vehiculos que han llegado nD



        File f = new File(pathLog);

        try {
            entrada = new BufferedReader(new FileReader(f));
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        if (f.exists()) {
            try {

                FileOutputStream out = new FileOutputStream(pathOut, true);

                PrintWriter miArchivo = new PrintWriter(out);
                miArchivo.write("Densidad" + "\t");
                miArchivo.write("Flujo" + "\t");


                miArchivo.println();
                miArchivo.close();

                System.out.println(entrada.readLine());



                String s;
                while ((s = entrada.readLine()) != null) {
                    //Separar campos
                    result = s.split(",");
                    objectID = result[0];
                    System.out.println(objectID);
                    evTime = Double.valueOf(result[1]).doubleValue();
                    segment = Integer.valueOf(result[2]).intValue();
                    evPos = Double.valueOf(result[3]).doubleValue();
                    evType = Integer.valueOf(result[4]).intValue();

                    if (segment == segToAnalyze) {

                        if (evTime > limitPeriod) {


                            d = nD - nQ;

                            if (nD != 0) {
                                q = nQ / nD;
                            } else {
                                q = 0;
                            }
                            out = new FileOutputStream(pathOut, true);

                            miArchivo = new PrintWriter(out);
                            miArchivo.write(d + "\t");
                            miArchivo.write(q + "\t");


                            miArchivo.println();
                            miArchivo.close();


                        }
                        if (evType == CE) {
                            nQ++;
                        } else {
                            if (evType == ALE || evType == AE) {

                                nD++;
                            }
                        }

                    }

                }
                System.out.println("Finished Analysis");


            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void main(String args[]) {
        //this.getDensityFlowLog_ver1(1,10.0,132.0,"c:/temp/logQD_ver1.txt");
        AnalyzerAgent analizer = new AnalyzerAgent();
        analizer.getDensityFlowLog_ver2(0, 10.0, "c:/temp/logQD_ver1_Calle0.txt");
        analizer.getDensityFlowLog_ver2(35, 10.0, "c:/temp/logQD_ver1_Calle35.txt");

    }
}